<?php
namespace app\frontend\forms;

use app\models\CanValidateInterface;
use Phalcon\Forms\Form;
use Phalcon\Forms\Element;

class FormBase extends Form
{
    public function getFirstMessageFor($name)
    {
        return $this->hasMessagesFor($name)?$this->getMessagesFor($name)->current():'';
    }

    public function hasMessage()
    {
        $messages = $this->getMessages(false);
        return count($messages) !== 0;
    }

    public function getFirstMessage()
    {
        $messages = $this->getMessages(false);
        return $this->hasMessage()?$messages->current():'';
    }

    protected function setElement(Element $element,$label = '',$attributes = []){
        if(!empty($attributes)){
            $element->setAttributes($attributes);
        }
        if($label){
            $element->setLabel($label);
        }
        if($element instanceof Element\Text || $element instanceof Element\Password){
            $element->setAttribute('placeholder','请输入'.$label);
        }

        $entity = $this->getEntity();
        if($entity instanceof CanValidateInterface) {
            $element->addValidators($entity->getRules($element->getName()));
        }


        $this->add($element);
    }
}